package gogm

/*
#include <openssl/evp.h>
#include <openssl/pem.h>
*/
import "C"

import (
	"errors"
	"runtime"
	"unsafe"
)

var (
	ErrCertificate = errors.New("Certificate error")
)

type Certificate struct {
	x509 *C.X509
}

func NewCertificateFromPEM(pem string, pass string) (*Certificate, error) {
	cpem := C.CString(pem)
	defer C.free(unsafe.Pointer(cpem))
	cpass := C.CString(pass)
	defer C.free(unsafe.Pointer(cpass))

	bio := C.BIO_new_mem_buf(unsafe.Pointer(cpem), -1)
	if bio == nil {
		return nil, ErrCertificate
	}
	defer C.BIO_free(bio)

	x509 := C.PEM_read_bio_X509(bio, nil, nil, unsafe.Pointer(cpass))
	if x509 == nil {
		return nil, ErrCertificate
	}

	ret := &Certificate{x509}
	runtime.SetFinalizer(ret, func(ret *Certificate) {
		C.X509_free(ret.x509)
	})

	return ret, nil
}

func (cert *Certificate) GetPublicKey() (*PublicKey, error) {
	pkey := C.X509_get_pubkey(cert.x509)
	if pkey == nil {
		return nil, ErrCertificate
	}

	ret := &PublicKey{pkey}
	runtime.SetFinalizer(ret, func(ret *PublicKey) {
		C.EVP_PKEY_free(ret.pkey)
	})
	return ret, nil
}

func (cert *Certificate) CheckPrivateKey(skey *PrivateKey) error {
	if 1 != C.X509_check_private_key(cert.x509, skey.pkey) {
		return ErrCertificate
	}

	return nil
}

func (cert *Certificate) CheckSignature(msg, sig []byte) error {
	pubkey, err := cert.GetPublicKey()
	if err != nil {
		return err
	}

	return SM2VerifyEx(pubkey, msg, sig)
}
